package com.changgou.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.FastDFSClient;
import com.changgou.util.FastDFSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file){
        try {
            //1.获取文件原始名
            String orgFileName = file.getOriginalFilename();

            //2.获取文件的扩展名
            //abc.1.txt

            int index = orgFileName.lastIndexOf(".");
            String extName = orgFileName.substring(index);


            //3.获取文件的内容
            byte[] content = file.getBytes();

            //4.封装上传文件对象
            FastDFSFile fastDFSFile = new FastDFSFile(orgFileName, content,  extName);

            //5.执行上传
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            //获取组名
            String groupName = uploadResult[0];
            //获取文件存储路径
            String remoteFileName = uploadResult[1];


            //6.拿到上传结果，拼接URL
            String url = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;

            logger.info("上传成功！url：{}",url);

            return new Result(true, StatusCode.OK, "上传成功", url);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传失败");
            return new Result(false, StatusCode.ERROR, "上传失败");
        }
    }

}
